from sc.model.models import Player, Map, Team, League, CommentarySet, Match, Game
from sc.model.meta import Session

class RetrievalService(object):
    def league(self, short_name):
        t = Session.query(League).filter(League.name_key == short_name)

        return t.one()

    def stage(self, league_short_name, stage_names):
        league = self.league(league_short_name)

        stages = []
        stage = league

        for next_stage_name in stage_names:
            stage = stage.stages[next_stage_name]
            stages.append(stage)

        return (league, stages)

    def match(self, league_short_name, stage_names,
            team_one_name_key, team_two_name_key):

        league, stages = self.stage(league_short_name, stage_names)

        def filter_func(x):
            return x.team_one.name_key == team_one_name_key and\
                x.team_two.name_key == team_two_name_key
                
        m = filter(filter_func, stages[-1].matches.values())

        return league, stages, m[0]

    def game(self, league_short_name, stage_names,
            team_one_name_key, team_two_name_key,
            game_number):

        league, stages, match = self.match(league_short_name,
                stage_names, team_one_name_key, team_two_name_key)

        try:
            game = match.games[game_number]
        except KeyError:
            game = None

        return league, stages, match, game

    def commentary_set(self, game_id, author):
        c = Session.query(CommentarySet)\
            .filter(CommentarySet.game_id == game_id)\
            .filter(CommentarySet.author == author).one()

        return c


